package com.woniuxy.demo.epai.controller.component;


import com.woniuxy.demo.epai.common.Result;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.util.List;

/**
 * controller初始化类
 */
public abstract class ControllerBase {

    /**
     * 时间转码
     *
     * @param binder 时间转换工具类
     */
    @InitBinder
    public void init(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 页面异常处理
     *
     * @param result 页面响应
     * @return 响应类
     */
    public Result extractError(BindingResult result) {
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            StringBuilder stringBuilder = new StringBuilder();
            for (FieldError fieldError : fieldErrors) {
                stringBuilder.append(fieldError.getField() + ":" + fieldError.getDefaultMessage() + ";");

            }
            return Result.fail(stringBuilder.toString());
        }
        return null;
    }


}
